﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;
using System.Windows.Forms;
using System.Drawing;

namespace iTunesAutomator
{
    class iTunesController
    {
        public static void CreatePlaylistsFromFolder(string path, RichTextBox textbox)
        {
            // Instantiate my awesome file manager!
            var fileManager = new FileManager() { RootPath = path };

            // Instantiate the COM iTunes object.          
            textbox.AppendStatus("Connecting to iTunes...");
            var iTunesApp = new iTunesAppClass();

            // Get Artists first
            var artistDirectories = fileManager.GetDirectories();

            // Now loop through each artist, grab the albums and start the add
            textbox.AppendStatus("Starting playlist creation from music folder...");
            foreach (var artistDirectory in artistDirectories)
            {
                // Now we have the albums for the artist.
                var albums = fileManager.GetDirectories(artistDirectory);
                var artistName = fileManager.GetDirectoryName(artistDirectory);

                // Loop through each album and add the songs to iTunes.
                textbox.AppendStatus("Creating playlists for artist: [" + artistName + "]");
                foreach (var album in albums)
                {
                    var albumName = fileManager.GetDirectoryName(album);
                    // This is where we append the artist name to the front of the album (artist - album).

                    var playlistName = artistName + " - " + albumName;

                    if (!PlaylistExists(playlistName, iTunesApp))
                    {
                        var playList = iTunesApp.CreatePlaylist(playlistName) as IITUserPlaylist;
                        // Add the songs to the playlist.
                        playList.AddFile(album);
                        textbox.AppendStatus("Created playlist: [" + playlistName + "] successfully!", Color.Green);
                    }
                    else
                    {
                        textbox.AppendStatus("Playlist: [" + playlistName + "] already exists!", Color.Red);
                    }
                }
            }
            textbox.AppendStatus("Playlist creation completed.", Color.Green);
        }

        private static bool PlaylistExists(string playlistName, iTunesAppClass iTunesApp)
        {
            var playLists = iTunesApp.LibraryPlaylist;
            foreach (IITPlaylist playlist in iTunesApp.LibrarySource.Playlists)
            {
                if (playlist.Name.ToLower() == playlistName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
    }
}
